package com.ncmem.up7;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;

public class PathTool {

    /**
     * 在linux中，getName()取出来的文件名称包含路径。需要手动去掉路径部分。
     * @param n
     * @return
     */
    public static String getName(String n){
        File f = new File(n);
        int pos = f.getName().lastIndexOf("\\");
        if(pos == -1) pos = f.getName().lastIndexOf("/");
        return f.getName().substring(pos+1);
    }

    public static String guid() {
        //简化
        return UUID.randomUUID().toString().replace("-","");
    }

    /**
     * 获取父级目录名称。
     * d:/upload/files/QQ2013.exe
     * 返回 d:/upload/files
     * @param p
     * @return
     */
    public static String getDirectoryName(String p)
    {
        File f = new File(p);
        String prt = f.getParent();
        return prt;
    }

    //返回值：exe
    public static String getExtention(String n)
    {
        String name = getName(n);

        int extIndex = name.lastIndexOf(".");
        //有扩展名
        if(-1 != extIndex)
        {
            String ext = name.substring(extIndex + 1);
            return ext;
        }
        return "";
    }

    public static Boolean exist(String v)
    {
        File f = new File(v);
        return f.exists();
    }

    public static void createDirectory(String v){

        File fd = new File(v);
        //fix():不创建文件夹
        if(!fd.exists()) fd.mkdirs();
    }

    //规范化路径，与操作系统保持一致。
    public static String canonicalPath(String v) throws IOException{
        File f = new File(v);
        return f.getCanonicalPath();
    }

    public static String combine(String a,String b)
    {
        boolean split = a.endsWith("\\");
        if(!split) split = a.endsWith("/");
        //没有斜杠
        if(!split)
        {
            return a.concat("/").concat(b);
            //return ps.getCanonicalPath().replace('\\', '/');
        }//有斜框
        else{
            return a.concat(b);
            //return ps.getCanonicalPath().replace('\\', '/');
        }
    }
    /**
     * 返回byte的数据大小对应的文本
     * @param size
     * @return
     */
    public static String getDataSize(long size){
        DecimalFormat formater = new DecimalFormat("####.00");
        if(size<1024){
            return size+"bytes";
        }else if(size<1024*1024){
            float kbsize = size/1024f;
            return formater.format(kbsize)+"KB";
        }else if(size<1024*1024*1024){
            float mbsize = size/1024f/1024f;
            return formater.format(mbsize)+"MB";
        }else if(size<1024*1024*1024*1024){
            float gbsize = size/1024f/1024f/1024f;
            return formater.format(gbsize)+"GB";
        }else{
            return "size: error";
        }
    }

    public static String url_decode(String v)
    {
        if(v== null) return "";
        if(StringUtils.isEmpty(v)) return "";

        v = v.replace("+","%20");
        try {
            v = URLDecoder.decode(v,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            v = "";
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//utf-8解码
        return v;
    }

    /**
     * 将字符串进行urlencode编码
     * 自动将+号替换成%20
     * @param v
     * @return
     */
    public static String url_encode(String v)
    {
        if(v== null) return "";
        if(StringUtils.isEmpty(v)) return "";

        try {
            v = URLEncoder.encode(v,"UTF-8");
            v = v.replace("+","%20");
        } catch (UnsupportedEncodingException e) {
            v = "";
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//utf-8解码
        return v;
    }

    /**
     * 将相对路径转换成绝对路径
     * @param ps res
     * @return /up6/imgs
     */
    public String MapPath(String ps)
    {
        // /up6
        String root = this.getRoot();

        if(StringUtils.isBlank(ps)) return root;

        //传值： /imgs
        if(!StringUtils.equals("/", ps.substring(0, 1))) root.contains("/");

        root = root.concat(ps);

        File f = new File(root);
        String path="";
        try {
            path = f.getCanonicalPath();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return path;
    }

    /**
     * 获取项目根目录
     * @return C:\\java\\tomcat\\7.0.47\\webapps\\up6
     */
    public String getRoot()
    {
        //前面会多返回一个"/", 例如  /D:/test/WEB-INF/, 奇怪, 所以用 substring()
        String path = this.getClass().getResource("/").getPath().substring(1).replaceAll("//", "/");
        if ( !StringUtils.isBlank(path) && !path.endsWith("/"))
        {
            path = path.concat("/");    //避免 WebLogic 和 WebSphere 不一致
        }
        path = path.replace("classes/", "");
        //D:/apache-tomcat-6.0.29/webapps/up6/WEB-INF/
        path = path.replace("%20", " ");//fix(2016-02-29):如果路径中包含空格,getPath会自动转换成%20
        //D:/apache-tomcat-6.0.29/webapps/up6
        path = path.replace("WEB-INF/", "");
        //D:/apache-tomcat-6.0.29/webapps/up6/

        File f = new File(path);
        //D:/apache-tomcat-6.0.29/webapps/Uploader6.1MySQL
        try {
            path = f.getCanonicalPath();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//取规范化的路径。
        return path;
    }

    public static String BytesToString(long byteCount)
    {
        String[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
        if (byteCount == 0)
            return "0" + suf[0];
        long bytes = Math.abs(byteCount);
        int place = (new Double(Math.floor(Math.log(bytes) / Math.log(1024))).intValue());
        double num = (double)bytes / Math.pow(1024, place);
        num = new BigDecimal(num).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
        return String.valueOf( (Math.signum(byteCount) * num) ) + suf[place];
    }
}
